<?php
	mysql_connect($globalDatabaseServer, $globalDatabaseUser, $globalDatabasePassword);
	mysql_select_db($globalDatabaseDatabase);
	
	$databaseYesterday = date('Y-m-d', mktime(0, 0, 0, date("m") , date("d") - 1, date("Y")));
	#$databaseYesterday = "";
	$databaseTimeSQLFilter = " WHERE ads.start LIKE '".$databaseYesterday."%'";
	
	function databaseQuery($sql) {
		#print "$sql\n";
		return mysql_query($sql);
	}
	
	# $result[user_id][] = array(category_id,array(keywords))
	function databaseGetObservers() {
		$query = databaseQuery("SELECT category_subscriptions.*, users.email
		                      FROM category_subscriptions
		                      INNER JOIN users ON users.id = category_subscriptions.user_id");
		$result = array();
		while ($data = mysql_fetch_assoc($query)) {
			$keywords = explode(",",$data['keywords']);
			$normalKeywords = array();
			foreach ($keywords as $keyword) {
				$normalized = strtolower($keyword);
				$normalized = trim($normalized);
				$normalKeywords[] = $normalized;
			}
			$result[$data['email']][$data['category_id']] = $normalKeywords;
		}
		return $result;
	}
	
	function databaseGetNewAdsFromYesterday() {
		global $globalDebug, $databaseTimeSQLFilter;
	
		$query = databaseQuery("SELECT ads.* FROM ads $databaseTimeSQLFilter");
		$result = array();
		while ($data = mysql_fetch_assoc($query)) {
			$result[$data['id']] = $data;
		}
		
		if ($globalDebug) {
			print "databaseGetNewAdsFromYesterday(): \n";
			print_r($result);
		}
		
		return $result;
	}
	
	function databaseGetCategoryAds() {
		global $globalDebug, $databaseTimeSQLFilter;
		
		$query = databaseQuery("SELECT ad_categories.*, ads.start
		                      FROM ad_categories
		                      INNER JOIN ads ON ads.id=ad_categories.ad_id
		                      $databaseTimeSQLFilter");
		$result = array();
		while ($data = mysql_fetch_assoc($query)) {
			$result[$data['category_id']][$data['ad_id']] = $data['ad_id'];
		}
		
		
		if ($globalDebug) {
			print "databaseGetCategoryAds(): \n";
			print_r($result);
		}
		
		return $result;
	}
	
	function databaseQueueEmail($receiver,$subject,$message) {
		$created = date("Y-m-d H:i:s");
		$sender = "noreply@tradingonrails.com";
		databaseQuery("INSERT INTO emails (message, created, receiver, sender, subject) VALUES ('".$message."','".$created."','".$receiver."','".$sender."','".$subject."')");
	}
	
	function databaseGetAllCategories($master=array(),$category=0) {
		$query = databaseQuery("SELECT * FROM categories");
		$result = array();
		while ($data = mysql_fetch_assoc($query)) {
			$result[$data['id']] = $data['category_id'];
		}
		return $result;
	}
?>
